package pl.edu.agh.uddiProxy.types;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKey;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.AccessType;
import org.springframework.security.context.SecurityContextHolder;

import pl.edu.agh.uddiProxy.dao.DAOHelper;

@Table(name = "serviceDynamicParameters",
	    uniqueConstraints = {@UniqueConstraint(columnNames={"tModelKey"})}
)
@AccessType("field")
@javax.persistence.Entity
public class ServiceDynamicParameters extends Entity {
	@Column(name = "tModelKey", nullable = false)
	private String tModelKey;
	@OneToMany(targetEntity = ParameterValue.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @MapKey(name="name")
    @JoinTable(name = "serviceDynamicParameters_map", joinColumns = @JoinColumn(name = "param_id"))
	private Map<String, ParameterValue> map;
	private static Map<String, ParameterType> parameterMap;
	@Transient
	private double distance;
	
	public ServiceDynamicParameters() {
		map = new HashMap<String, ParameterValue>();
		if (DAOHelper.getParametersMap() != null) {
			initMap();
		}
	}
	
	public void initMap() {
		parameterMap = DAOHelper.getParametersMap().getParametersMap();
		for (String key : parameterMap.keySet()) {
			if (!map.containsKey(key)) {
				String value = parameterMap.get(key).getInitValue();
				map.put(key, new ParameterValue(key, value));
			}
		}
	}
	
	public ServiceDynamicParameters(String modelKey) {
		this();
		tModelKey = modelKey;
	}

	public String getTModelKey() {
		return tModelKey;
	}

	public void setTModelKey(String modelKey) {
		tModelKey = modelKey;
	}

	public ParameterValue getParameterValue(String name) {
		return map.get(name);
	}

	public void updateParameter(String parameterName, String value) {
		if (parameterMap == null) {
			initMap();
		}
		
		Permission permission = parameterMap.get(parameterName).getPermission();
		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		if ((permission.equals(Permission.EVERYONE) || (permission.equals(Permission.OWNER) && user.isOwner(tModelKey) )) 
				&& value != null && value.length() > 0) {
			Object v;
			if (parameterMap.get(parameterName).getType().equals(ValueType.DOUBLE)) {
				v = Double.parseDouble(value);
			} else if (parameterMap.get(parameterName).getType().equals(ValueType.INTEGER)) {
				v = Integer.parseInt(value);
			} else if (parameterMap.get(parameterName).getType().equals(ValueType.LONG)) {
				v = Long.parseLong(value);
			} else  {
				v = value;
			}
			AverageCounter counter = parameterMap.get(parameterName).getCounter();
			counter.count(parameterMap.get(parameterName), getParameterValue(parameterName), v);
		}
	}
	
	protected void setParameter(String name, String value) {
		ParameterType type = parameterMap.get(name);
		if (type.getType().isNumber() && value != null && value.length() > 0) {
			double v = Double.parseDouble(value);
			if (type.getMaxValue() != null && type.getMaxValue().length() > 0) {
				double max = Double.parseDouble(type.getMaxValue());
				if (v > max) {
					throw new IllegalArgumentException(name + "must be <= " + max);
				}
			}
			if (type.getMinValue() != null && type.getMinValue().length() > 0) {
				double min = Double.parseDouble(type.getMinValue());
				if (v < min) {
					throw new IllegalArgumentException(name + "must be >= " + min);
				}
			}
			map.get(name).setValue(value);
		}
	}

	public void setDistanceValue(double value) {
		distance = value;
	}
	
	public double getDistanceValue() {
		return distance;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((tModelKey == null) ? 0 : tModelKey.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ServiceDynamicParameters other = (ServiceDynamicParameters) obj;
		if (tModelKey == null) {
			if (other.tModelKey != null)
				return false;
		} else if (!tModelKey.equals(other.tModelKey))
			return false;
		return true;
	}
	
	@Override
	public String toString() {
		return tModelKey + " " + map;
	}
}
